package com.hethongviet.vending.pages;

import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.android.DemoKit.DemoKitActivity;
import com.hethongviet.vending.AppConfig;
import com.hethongviet.vending.AppMain;
import com.hethongviet.vending.Constant;
import com.google.android.DemoKit.R;
import com.hethongviet.vending.Utils;
import com.hethongviet.vending.helper.OnUsbListener;
import com.hethongviet.vending.helper.call.ListenPhoneCallService;
import com.hethongviet.vending.helper.db.AccountSQLite;
import com.hethongviet.vending.helper.db.ProductSellSQLite;
import com.hethongviet.vending.helper.db.ProductServiceSQLite;
import com.hethongviet.vending.helper.dialog.DialogMessageBack;
import com.hethongviet.vending.helper.dialog.DialogMessageConfirm;
import com.hethongviet.vending.helper.dialog.DialogMessageTimeOut;
import com.hethongviet.vending.model.Account;
import com.hethongviet.vending.model.MachineInfo;
import com.hethongviet.vending.model.ProductSell;
import com.hethongviet.vending.model.ProductService;
import com.hethongviet.vending.model.Transaction;
import com.hethongviet.vending.network.CONSTANTS;
import com.hethongviet.vending.network.Network;

public class StandbyActivity extends DemoKitActivity implements Runnable
{
	// private int _textSloganRemain = 0;
	// private int _textSloganIndex = 0;
	private boolean _isSloganProduct = false;

	private static final int TOTAL_SLOGANS = 3;
	private int _textSloganTopMargin[] = null;
	private TextView _textViewSlogan[] = null;

	private Button _buttonLoginUser = null;
	private Button _buttonLoginService = null;
	private Button _buttonLoginAdmin = null;
	private Button _buttonSendUsb = null;

	private ViewGroup _layoutBG = null;
	private static final int TOTAL_DRAWABLES = 4;
	private int[] _drawable = null;
	private int _drawableIndex = 0;
	private Timer _timerAdvertisement = null;
	// private Timer _timerTextSlogan = null;

	private Timer _timerUpdateData = null;

	private AccountSQLite _accountSqLite = null;

	private boolean isWaitedForLogin = false;

	private static StandbyActivity instance = null;

	private OnUsbListener mOnUsbListener = null; 
	
	public static StandbyActivity getInstance()
	{
		return instance;
	}

	@Override
	public void onAttachedToWindow()
	{
		if (AppConfig.USE_ATTACH_WINDOW_FOR_DISABLE_HOME_KEY)
		{
			this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
			super.onAttachedToWindow();
		}
	}

	public StandbyActivity()
	{
		_textSloganTopMargin = new int[TOTAL_SLOGANS];
		_textViewSlogan = new TextView[TOTAL_SLOGANS];
		_drawable = new int[TOTAL_DRAWABLES];
		_accountSqLite = new AccountSQLite(this);

		instance = this;
	}

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		setContentView(R.layout.page_standby);

		_buttonLoginUser = (Button) findViewById(R.id.button_login_user);
		_buttonLoginService = (Button) findViewById(R.id.button_login_service);
		_buttonLoginAdmin = (Button) findViewById(R.id.button_login_admin);
		_buttonSendUsb = (Button) findViewById(R.id.button_debug_usb);

		try
		{
			openFileInput("usb");

		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}

		if (!AppConfig.IS_DEBUG_BUTTON_USB)
		{
			_buttonSendUsb.setVisibility(View.INVISIBLE);
		}

		_buttonSendUsb.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
//				usbSend("123213242");
//				usbSend("1");
//				sendCommand((byte)5, (byte)5, (byte)5);
				sendCommand((byte)5, (byte)5, (byte)7);
			}
		});

		if (AppConfig.IS_DEBUG_BUTTON_LOGIN)
		{
			// AppMain.getInstance()._machineInfo = new MachineInfo("VM01",
			// "01645401194", 40,
			// "5C:17:D3:9B:2E:76", "00:12:03:09:14:98");//LG P350

			_buttonLoginUser.setOnClickListener(new OnClickListener()
			{

				@Override
				public void onClick(View arg0)
				{
					loginAsUser(new Account("0903946510"));
				}
			});

			_buttonLoginService.setOnClickListener(new OnClickListener()
			{

				@Override
				public void onClick(View arg0)
				{
					loginAsSalesMan(new Account("0903946510"));
				}
			});

			_buttonLoginAdmin.setOnClickListener(new OnClickListener()
			{

				@Override
				public void onClick(View arg0)
				{
					loginAsAdmin(new Account("0903946510"));
				}
			});
		}
		else
		{
			_buttonLoginService.setVisibility(View.GONE);
			_buttonLoginUser.setVisibility(View.GONE);
			_buttonLoginAdmin.setVisibility(View.GONE);
		}

		prepareForNumber();

		_layoutBG = (RelativeLayout) findViewById(R.id.background);

		if (AppConfig.USE_IMAGE_SLOGAN)
		{
			_textViewSlogan[0] = (TextView) findViewById(R.id.text_slogan_1);
			_textViewSlogan[1] = (TextView) findViewById(R.id.text_slogan_2);
			_textViewSlogan[2] = (TextView) findViewById(R.id.text_slogan_3);

			_textSloganTopMargin[0] = ((LinearLayout.LayoutParams) _textViewSlogan[0].getLayoutParams()).topMargin;
			_textSloganTopMargin[1] = ((LinearLayout.LayoutParams) _textViewSlogan[1].getLayoutParams()).topMargin;
			_textSloganTopMargin[2] = ((LinearLayout.LayoutParams) _textViewSlogan[2].getLayoutParams()).topMargin;

			Utils.debug("SLOGAN : location Y of text: "
					+ _textSloganTopMargin[0] + "; " + _textSloganTopMargin[1]
					+ "; " + _textSloganTopMargin[2]);

			TimerTask timerTask = new TimerTask()
			{

				@Override
				public void run()
				{
					_isSloganProduct = !_isSloganProduct;
					// Utils.debug("DEBUG SLOGAN -------- update!!! isproduct = "
					// + _isSloganProduct);
					onUpdateSlogan();
				}
			};

			_timerAdvertisement = new Timer();
			_timerAdvertisement.scheduleAtFixedRate(timerTask, 0,
					Constant.TIME_SLOGAN_STEP);

		}
		else
		{
			_drawable[0] = R.drawable.ad1;
			_drawable[1] = R.drawable.ad2;
			_drawable[2] = R.drawable.ad3;
			_drawable[3] = R.drawable.ad4;

			TimerTask timerTask = new TimerTask()
			{

				@Override
				public void run()
				{
					onUpdateAdvertisement();
				}
			};

			_timerAdvertisement = new Timer();
			_timerAdvertisement.scheduleAtFixedRate(timerTask, 0,
					Constant.TIME_ADVERTISEMENT_STEP);
		}

	}

	private void prepareForNumber()
	{

		TextView textViewLoginNumber = (TextView) findViewById(R.id.message_login_mobile);

		if (AppConfig.USE_ACCOUNT_MONEY)
		{
			ImageView imageViewQRCode = (ImageView) findViewById(R.id.image_qr_code);
			TextView textViewLoginQRCode = (TextView) findViewById(R.id.message_login_qr_code);

			imageViewQRCode.setVisibility(View.GONE);
			textViewLoginNumber.setVisibility(View.GONE);
			textViewLoginQRCode.setVisibility(View.GONE);
		}
		else
		{
			TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
			textViewLoginNumber.setText(getString(R.string.message_login_mobile)
					+ " " + "01634174389"
			// telephonyManager.getLine1Number()
			);

			Utils.debug("getLine1Number " + telephonyManager.getLine1Number());
			Utils.debug("getDeviceId " + telephonyManager.getDeviceId());
			Utils.debug("getDeviceSoftwareVersion "
					+ telephonyManager.getDeviceSoftwareVersion());
			Utils.debug("getNetworkCountryIso "
					+ telephonyManager.getNetworkCountryIso());
			Utils.debug("getNetworkOperator "
					+ telephonyManager.getNetworkOperator());
			Utils.debug("getNetworkOperatorName "
					+ telephonyManager.getNetworkOperatorName());
			Utils.debug("getNetworkType " + telephonyManager.getNetworkType());
			Utils.debug("getPhoneType " + telephonyManager.getPhoneType());
			Utils.debug("getSimCountryIso "
					+ telephonyManager.getSimCountryIso());
			Utils.debug("getSimOperator " + telephonyManager.getSimOperator());
			Utils.debug("getSimOperatorName "
					+ telephonyManager.getSimOperatorName());
			Utils.debug("getSimSerialNumber "
					+ telephonyManager.getSimSerialNumber());
			Utils.debug("getSimState " + telephonyManager.getSimState());
			Utils.debug("getSubscriberId " + telephonyManager.getSubscriberId());
			Utils.debug("getVoiceMailAlphaTag "
					+ telephonyManager.getVoiceMailAlphaTag());
			Utils.debug("getVoiceMailNumber "
					+ telephonyManager.getVoiceMailNumber());

			// 10-02 01:12:45.957: D/Debug(13039): @@@@@@@@@@@@@@@@@@@@@@@
			// getLine1Number
			// 10-02 01:12:45.960: D/Debug(13039): @@@@@@@@@@@@@@@@@@@@@@@
			// getDeviceId 357453043792142
			// 10-02 01:12:45.960: D/Debug(13039): @@@@@@@@@@@@@@@@@@@@@@@
			// getDeviceSoftwareVersion 01
			// 10-02 01:12:45.960: D/Debug(13039): @@@@@@@@@@@@@@@@@@@@@@@
			// getNetworkCountryIso vn
			// 10-02 01:12:45.960: D/Debug(13039): @@@@@@@@@@@@@@@@@@@@@@@
			// getNetworkOperator 45201
			// 10-02 01:12:45.960: D/Debug(13039): @@@@@@@@@@@@@@@@@@@@@@@
			// getNetworkOperatorName VN MOBIFONE
			// 10-02 01:12:45.960: D/Debug(13039): @@@@@@@@@@@@@@@@@@@@@@@
			// getNetworkType 3
			// 10-02 01:12:45.960: D/Debug(13039): @@@@@@@@@@@@@@@@@@@@@@@
			// getPhoneType 1
			// 10-02 01:12:45.960: D/Debug(13039): @@@@@@@@@@@@@@@@@@@@@@@
			// getSimCountryIso vn
			// 10-02 01:12:45.960: D/Debug(13039): @@@@@@@@@@@@@@@@@@@@@@@
			// getSimOperator 45201
			// 10-02 01:12:45.960: D/Debug(13039): @@@@@@@@@@@@@@@@@@@@@@@
			// getSimOperatorName
			// 10-02 01:12:45.964: D/Debug(13039): @@@@@@@@@@@@@@@@@@@@@@@
			// getSimSerialNumber 8984011202921118358
			// 10-02 01:12:45.964: D/Debug(13039): @@@@@@@@@@@@@@@@@@@@@@@
			// getSimState 5
			// 10-02 01:12:45.964: D/Debug(13039): @@@@@@@@@@@@@@@@@@@@@@@
			// getSubscriberId 452014110241971
			// 10-02 01:12:45.964: D/Debug(13039): @@@@@@@@@@@@@@@@@@@@@@@
			// getVoiceMailAlphaTag Voicemail
			// 10-02 01:12:45.968: D/Debug(13039): @@@@@@@@@@@@@@@@@@@@@@@
			// getVoiceMailNumber null
		}
	}

	private void processAccount(Account account)
	{
		if (AppConfig.USE_ACCOUNT_DATABASE)
		{
			AppMain.getInstance().setCurrentAccount(
					_accountSqLite.getById(account.getId()));

			if (AppMain.getInstance().getCurrentAccount() == null)
			{
				Utils.debug("Error: Can not get the account...");
				return;
			}

			Utils.debug("get account="
					+ AppMain.getInstance().getCurrentAccount().getId());
		}
		else
		{
			AppMain.getInstance().setCurrentAccount(account);
		}
	}

	private void loginAsSalesMan(Account account)
	{
		processAccount(account);

		Intent intent = new Intent(StandbyActivity.this,
				ServiceModeActivity.class);
		startActivity(intent);
	}

	private void loginAsAdmin(Account account)
	{
		processAccount(account);

		Intent intent = new Intent(StandbyActivity.this, AdminActivity.class);
		startActivity(intent);
	}

	private void loginAsUser(Account account)
	{
		processAccount(account);

		pauseTimerUpdateData();

		Intent intent = new Intent(StandbyActivity.this, UserActivity.class);
		startActivity(intent);
	}

	private int _timeUpdateDataRemain = Constant.TIME_UPDATE_DATA;
	private int _timeUpdateDataSave = Constant.TIME_UPDATE_DATA;;

	private void startTimerUpdateData()
	{

		Utils.debug("Starting time out for update data!!");

		TimerTask timerTaskUpdateData = new TimerTask()
		{

			@Override
			public void run()
			{
				_timeUpdateDataRemain -= Constant.TIME_OUT_STEP;

				if (_timeUpdateDataRemain <= 0)
				{
					_timerUpdateData.cancel();
					_timerUpdateData = null;

					_timeUpdateDataRemain = Constant.TIME_UPDATE_DATA;
					_timeUpdateDataSave = Constant.TIME_UPDATE_DATA;

					if (AppConfig.USE_SEND_ALL_DATA)
					{
						/* Update data */
						Intent intent = new Intent(StandbyActivity.this,
								PauseActivity.class);
						intent.putExtra(PauseActivity.EXTRA_REQUEST_TYPE,
								Constant.REQUEST_UPDATE_DATA);
						startActivity(intent);
					}
					else
					{
						MachineInfo machineInfo = AppMain.getInstance().getMachineInfo();

						ProductSellSQLite productSellSQLite = new ProductSellSQLite(
								StandbyActivity.this);
						List<ProductSell> productSells = productSellSQLite.getAll();
						for (Iterator<ProductSell> iterator = productSells.iterator(); iterator.hasNext();)
						{
							ProductSell productSell = (ProductSell) iterator.next();
							if (!productSell.isSentServerOk())
							{
								Network.sendProductSell(productSell,
										machineInfo);
							}
						}

						ProductServiceSQLite productServiceSQLite = new ProductServiceSQLite(
								StandbyActivity.this);
						List<ProductService> productServices = productServiceSQLite.getAll();
						for (Iterator<ProductService> iterator = productServices.iterator(); iterator.hasNext();)
						{
							ProductService productService = (ProductService) iterator.next();
							if (!productService.isSentServerOk())
							{
								if (productService.getTransaction() == ProductService.TRANSACTION_PRODUCT_CHANGE)
								{
									Network.sendProductChange(productService);
								}
								else if (productService.getTransaction() == ProductService.TRANSACTION_PRODUCT_PUT_IN)
								{
									Network.sendProductPutIn(productService);
								}
								else
								{
									Network.sendProductTakeOut(productService);
								}
							}
						}
					}
				}
			}
		};
		_timeUpdateDataRemain = _timeUpdateDataSave;
		_timerUpdateData = new Timer();
		_timerUpdateData.scheduleAtFixedRate(timerTaskUpdateData, 0,
				Constant.TIME_OUT_STEP);

	}

	private void pauseTimerUpdateData()
	{
		Utils.debug("Pause time out for update data!!");
		_timeUpdateDataSave = _timeUpdateDataRemain;
		stopTimerUpdateData();

	}

	private void stopTimerUpdateData()
	{
		_timerUpdateData.cancel();
		_timerUpdateData = null;

	}

	@Override
	public void onResume()
	{
		AppMain.getInstance().setStandbyScreen(true);

		/* Start timer for update data to server */
		startTimerUpdateData();

		mOnUsbListener = null;
		
		super.onResume();

	}

	@Override
	protected void onStop()
	{
		AppMain.getInstance().setStandbyScreen(false);
		super.onStop();
	}

	@Override
	public void onDestroy()
	{
		Utils.debug("Standby activity ------------ destroy");

		stopService(new Intent(this, ListenPhoneCallService.class));

		super.onDestroy();
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event)
	{
		if (KeyEvent.KEYCODE_MENU == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_LEFT == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_DOWN == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_RIGHT == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_UP == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_CENTER == event.getKeyCode()
				|| KeyEvent.KEYCODE_CALL == event.getKeyCode()
				|| KeyEvent.KEYCODE_CAMERA == event.getKeyCode()
				|| KeyEvent.KEYCODE_ENDCALL == event.getKeyCode()
				|| KeyEvent.KEYCODE_HOME == event.getKeyCode()
				|| KeyEvent.KEYCODE_SEARCH == event.getKeyCode()
				|| KeyEvent.KEYCODE_BACK == event.getKeyCode())
		{
			return Utils.disableAllKey(event);
		}
		else
			return super.dispatchKeyEvent(event);

	}

	@Override
	protected Dialog onCreateDialog(int id)
	{
		if (id == R.string.message_user_not_egister)
		{
			return new DialogMessageBack(this, false, id, false);
		}
		else if (id == R.string.message_error_account_have_no_money)
		{
			final DialogMessageConfirm dialogInputMoneyCode = new DialogMessageConfirm(
					this, false, id, false);

			OnClickListener onClickListenerYES = new OnClickListener()
			{

				@Override
				public void onClick(View v)
				{

					Intent intent = new Intent(StandbyActivity.this,
							InputTextActivity.class);

					Bundle bundle = new Bundle();
					bundle.putInt(InputTextActivity.KEY_INPUT_TYPE,
							InputTextActivity.INPUT_USER_AMOUNT);
					bundle.putInt(Constant.EXTRA_FINISH, 1);
					intent.putExtras(bundle);

					startActivityForResult(intent,
							InputTextActivity.INPUT_USER_AMOUNT);

					dialogInputMoneyCode.cancel();
				}
			};

			OnClickListener onClickListenerNo = new OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					dialogInputMoneyCode.cancel();
				}
			};

			dialogInputMoneyCode.setOnclickListenerYes(onClickListenerYES);
			dialogInputMoneyCode.setOnclickListenerNo(onClickListenerNo);
			return dialogInputMoneyCode;
		}
		else if (id == R.string.message_bluetooth_not_available)
		{
			return new DialogMessageBack(this, true, id, false);
		}
		else if (id == R.string.message_success_pay_money_in)
		{
			final DialogMessageTimeOut dialogMessageTimeOut = new DialogMessageTimeOut(
					this,
					String.format(
							getString(id),
							AppMain.getInstance().getCurrentAccount().getAmount()),
					true);

			TimerTask timerTask = new TimerTask()
			{
				@Override
				public void run()
				{
					loginAsUser(AppMain.getInstance().getCurrentAccount());
					dialogMessageTimeOut.hide();
				}
			};

			dialogMessageTimeOut.setTimeTask(timerTask);

			return dialogMessageTimeOut;
		}
		else
		{
			return createDialogStatusServer(id);
		}
	}

	private void onUpdateSlogan()
	{
		runOnUiThread(new Runnable()
		{

			@Override
			public void run()
			{
				if (_isSloganProduct)
				{
					_layoutBG.setBackgroundColor(Color.parseColor("#f7d7d7"));

					for (int i = 0; i < TOTAL_SLOGANS; i++)
					{
						_textViewSlogan[i].setText(getString(R.string.slogan_slide_1
								+ i));
					}

				}
				else
				{
					_layoutBG.setBackgroundColor(Color.parseColor("#e5e8c0"));

					for (int i = 0; i < TOTAL_SLOGANS; i++)
					{
						_textViewSlogan[i].setText(getString(R.string.slogan_slide_product_1
								+ i));
					}
				}
			}
		});

	}

	private void onUpdateAdvertisement()
	{
		this.runOnUiThread(new Runnable()
		{

			@Override
			public void run()
			{
				_layoutBG.setBackgroundDrawable(getResources().getDrawable(
						_drawable[_drawableIndex++]));
				_drawableIndex = (_drawableIndex == TOTAL_DRAWABLES) ? 0
						: _drawableIndex;
			}
		});
	}

	@Override
	public void onNetworkTimeOut(Transaction transaction)
	{
		isWaitedForLogin = false;

		hideProgressDialog();
		showDialogWithCatch(R.string.message_time_out_network);

		Utils.debug("Network timeout -----------------");
	}

	@Override
	public void onNetworkMessageIncomming(final Transaction transaction)
	{
		if (transaction == null)
		{
			Utils.debug("Null -----------received");
			return;
		}

		final String message = transaction.getMessageReceived();
		Utils.debug("Receive message = " + message);

		if (message == null || message.equals(""))
		{
			Utils.debug("Null message!!!!!!!!");
			return;
		}

		hideProgressDialog();

		if (transaction.getMethodSent().equals(CONSTANTS.SERVICE.LOGIN))
		{
			isWaitedForLogin = false;

			String[] strings = transaction.getMessageReceived().split("[:]");

			if (strings == null || strings.length < 2)
			{
				showDialogWithCatch(R.string.message_error_login);
				Utils.debug("Wrong message!!!!!!!!");
				return;
			}

			if (AppMain.getInstance().getCurrentAccount() == null)
			{
				AppMain.getInstance().setCurrentAccount(new Account());
			}

			AppMain.getInstance().getCurrentAccount().setName(strings[0]);
			AppMain.getInstance().getCurrentAccount().setId(
					((Account) (transaction.getModel())).getId());

			if (strings[1].equalsIgnoreCase(CONSTANTS.SERVICE.RESULT_LOGIN_BUYER)
					|| strings[1].equalsIgnoreCase(CONSTANTS.SERVICE.RESULT_LOGIN_SALES_MAN)
					|| strings[1].equalsIgnoreCase(CONSTANTS.SERVICE.RESULT_LOGIN_ADMIN))
			{

				if (strings[1].equalsIgnoreCase(CONSTANTS.SERVICE.RESULT_LOGIN_BUYER))
				{
					loginAsUser((Account) transaction.getModel());
				}
				else if (strings[1].equalsIgnoreCase(CONSTANTS.SERVICE.RESULT_LOGIN_ADMIN))
				{
					loginAsAdmin((Account) transaction.getModel());
				}
				else
				{
					loginAsSalesMan((Account) transaction.getModel());
				}

			}
			else
			{
				showDialogWithCatch(R.string.message_error_login);
			}
		}
		else if (transaction.getMethodSent().equals(
				CONSTANTS.SERVICE.ADD_PRODUCT_CHANGE)
				|| transaction.getMethodSent().equals(
						CONSTANTS.SERVICE.ADD_PRODUCT_PUTIN)
				|| transaction.getMethodSent().equals(
						CONSTANTS.SERVICE.ADD_PRODUCT_TAKEOUT))
		{
			if (transaction.getMessageReceived().toUpperCase().contains("OK"))
			{
				ProductService productService = (ProductService) transaction.getModel();
				productService.setSentServerOk(true);

				ProductServiceSQLite productServiceSQLite = new ProductServiceSQLite(
						this);
				productServiceSQLite.insert(productService);
			}
		}
		else if (transaction.getMethodSent().equals(
				CONSTANTS.SERVICE.ADD_PRODUCT_SELLOUT))
		{
			if (transaction.getMessageReceived().toUpperCase().contains("OK"))
			{
				ProductSell productSell = (ProductSell) transaction.getModel();
				productSell.setSentServerOk(true);

				ProductSellSQLite productSellSQLite = new ProductSellSQLite(
						this);
				productSellSQLite.insert(productSell);
			}
		}
	}

	@Override
	public void onConnectFail(int typeError)
	{
		isWaitedForLogin = false;

		Utils.debug("Connect fail!.......................");
		hideProgressDialog();

		showDialogWithStatus(typeError);
	}

	@Override
	public void onReceivedUsbMessage(String message)
	{
		if (TextUtils.isEmpty(message))
		{
			Utils.debug("Null message usb!!!!!");
			return;
		}

		Utils.debug("Full usb message : " + message);
		debugToastUsb("Full usb message : " + message);

		if(mOnUsbListener != null)
		{
			mOnUsbListener.onReceivedUsbMessage(message);
			return;
		}
		
		/* Get message RFID and send to server for login */

		if (AppConfig.USE_ACCOUNT_MONEY)
		{
			String[] strings = message.split("[:]");
			if (strings != null && strings.length == 2)
			{
				Account account = new Account(strings[0]);
				account.setName(strings[0]);

				int amount = 0;
				try
				{
					amount = Integer.parseInt(strings[1]);
				} catch (NumberFormatException e)
				{
					e.printStackTrace();
				}

				if (amount <= 0)
				{
					AppMain.getInstance().setCurrentAccount(account);
					showDialogWithCatch(R.string.message_error_account_have_no_money);
					return;
				}

				Utils.debug("Login with valid barcode!!!!!!!!!!!!");
				account.setAmount(amount);
				loginAsUser(account);

				return;
			}

			Utils.debug("wrong barcode!!!!!!!!!!!!");
			return;
		}

		if (!isWaitedForLogin)
		{
			if (!AppConfig.IS_NETWORK_AVAILABLE)
			{
				Transaction transaction = new Transaction();
				transaction.setMethodSent(CONSTANTS.SERVICE.LOGIN);
				transaction.setMessageReceived("Dinh Ngoc Tan:BUYER");
				transaction.setModel(new Account("0942478466"));

				onNetworkMessageIncomming(transaction);
				return;
			}
			else
			{
				isWaitedForLogin = true;
				Network.sendRequestLogin(
						AppMain.getInstance().getMachineInfo().getCode(),
						message.substring(0, message.length() - 1));

				showProgress(StandbyActivity.this);
			}
		}
	}

	@Override
	public void onIncomingCall(final String cellPhoneIncoming)
	{
		Utils.debug("Receiver and process call!!!!!!!!!!!!!!!!!");

		runOnUiThread(new Runnable()
		{

			@Override
			public void run()
			{
				/**
				 * For ADMIN debug - reset, reinstall the APP
				 * */
				if (cellPhoneIncoming.equals(Constant.NUMBER_DEBUG_EXIT_APP))
				{
					Utils.debug("Debug Exit program!!!!!!!!!!!!!");
					moveTaskToBack(true);
					return;
				}

				/**
				 * For ADMIN goto the service mode
				 * */
				if (cellPhoneIncoming.equals(Constant.NUMBER_DEBUG_SALESMAN))
				{
					Utils.debug("Debug goto service mode!!!!!!!!!!!!!");
					loginAsSalesMan(new Account(cellPhoneIncoming));
					return;
				}

				/**
				 * For ADMIN goto the buyer mode
				 * */
				if (cellPhoneIncoming.equals(Constant.NUMBER_DEBUG_BUYER))
				{
					Utils.debug("Debug goto buyer mode!!!!!!!!!!!!!");
					loginAsUser(new Account(cellPhoneIncoming));
					return;
				}

				/**
				 * For ADMIN goto the admin mode
				 * */
				if (cellPhoneIncoming.equals(Constant.NUMBER_DEBUG_ADMIN))
				{
					Utils.debug("Debug goto buyer mode!!!!!!!!!!!!!");
					loginAsAdmin(new Account(cellPhoneIncoming));
					return;
				}

				/**
				 * For ADMIN goto the admin mode
				 * */
				if (cellPhoneIncoming.equals(Constant.NUMBER_DEBUG_ADMIN_1))
				{
					Utils.debug("Debug goto buyer mode!!!!!!!!!!!!!");
					loginAsAdmin(new Account(cellPhoneIncoming));
					return;
				}

				if (!isWaitedForLogin)
				{
					if (!AppConfig.IS_NETWORK_AVAILABLE)
					{
						Transaction transaction = new Transaction();
						transaction.setMethodSent(CONSTANTS.SERVICE.LOGIN);
						transaction.setMessageReceived("Dinh Ngoc Tan:SALESMAN");

						Account account = new Account();
						account.setId("0942478466");
						transaction.setModel(account);

						onNetworkMessageIncomming(transaction);

						return;
					}
					else
					{
						Network.sendRequestLogin(
								AppMain.getInstance().getMachineInfo().getCode(),
								cellPhoneIncoming);

						showProgress(StandbyActivity.this);
					}
				}
			}
		});
	}

	@Override
	public void showProgress(Activity activity)
	{
		if (!isWaitedForLogin)
			return;
		_progressDialog = ProgressDialog.show(this, "",
				activity.getString(R.string.please_wait), true, false);
	}

	public OnUsbListener getOnUsbListener()
	{
		return mOnUsbListener;
	}

	public void setOnUsbListener(OnUsbListener mOnUsbListener)
	{
		this.mOnUsbListener = mOnUsbListener;
	}
}
